<?php
/**
 * @Description: 任教学科
 * @Author: kzj
 * @datetime: 2023-02-24
 */
namespace App\Services\Education;

use App\Http\Controllers\Excel\ExcelExport;
use App\Models\Educaton\MasterTeacher;
use App\Models\FormInstance;
use App\Models\System\Tasks;
use App\Models\System\Term;
use App\Models\SystemTask;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 任教学科 (服务)
 */
class HeadMasterService
{
    /** @var \App\Repositories\Education\HeadMasterRepository $headMasterRepository */
    private $headMasterRepository;
    /** @var \App\Repositories\System\DictionaryItemRepository $dictionaryItemRepository */
    private $dictionaryItemRepository;

    private $formKey = 'EW_CLASS_TEACHER_TABLE';

    public function __construct()
    {
        $this->headMasterRepository = app('headMasterRepository');
        $this->dictionaryItemRepository = app('dictionaryItemRepository');
    }


    /**
     * @Description: 班主任列表信息数据
     * @Author: kzj
     * @datetime: 2022-11-21
     */
    public function getList($request)
    {
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 10;
        // dd($request);
        $termId = 0;
        $classId = 0;
        $chiefId = 0;
        $rangeDate = [];
        $creatorName = ''; //创建人
        $jsonSearch =  [];
        $where = ['master_teacher.deleted' => 0];
        if (isset($request['search']['data_version_id'] )&& !empty($request['search']['data_version_id'])){
            $termId = $request['search']['data_version_id'];
        }
        if (isset($request['search']['class_value'] )&& !empty($request['search']['class_value'])){
            $classId = $request['search']['class_value'];
        }
        if (isset($request['search']['chief_value'] )&& !empty($request['search']['chief_value'])){
            $chiefId = $request['search']['chief_value'];
        }
        if (isset($request['search']['date_range'] )&& !empty($request['search']['date_range'])){
            $rangeDate = explode(' - ', $request['search']['date_range']);
        }
        if (isset($request['search']['creator_name'] )&& !empty($request['search']['creator_name'])){
            $creatorName = $request['search']['creator_name'];
        }
        if (isset($request['search']['grade'] )&& !empty($request['search']['grade'])){
            $jsonSearch['grade_value'] = $request['search']['grade'];
        }
        if (isset($request['search']['class_item'] )&& !empty($request['search']['class_item'])){
            $jsonSearch['class_value'] = $request['search']['class_item'];
        }
        !empty($request['search']['status'])     && $where['b.status'] = $request['search']['status'];
        $user = Auth::user();

        $result = MasterTeacher::where($where)
            ->leftJoin('form_instance as b' ,'master_teacher.form_instance_id','=','b.id')
            ->select('master_teacher.*')
            /**
            ->when(!$user->is_checker, function($q) use($user){
                $q->where('user_id', $user->id);
            })**/
            ->when(!empty($jsonSearch), function($q) use($jsonSearch) {
                foreach($jsonSearch as $k => $id) {
                    $q->whereRaw(" JSON_EXTRACT(master_teacher.`".$k."`,'$[0].optionId') = $id");
                }
            })
            ->when(isset($request['user_id']) && !empty($request['user_id']), function($q) use($request){
                $q->where('master_teacher.user_id', $request['user_id']);//处理档案袋只查看自己的数据
            })
            ->when($termId > 0, function($q) use($termId) {
                $q->whereHas('term', function ($query) use($termId) {
                    $query->where('id', $termId);
                });
            })
            ->when($classId > 0, function($q) use($classId) {
                $q->whereRaw(" JSON_EXTRACT(master_teacher.`class_value`,'$[0].optionId') = $classId");
            })
            ->when($chiefId > 0, function($q) use($chiefId) {
                $q->whereRaw(" JSON_EXTRACT(master_teacher.`chief_value`,'$[0].optionId') = $chiefId");
            })
            ->when(!empty($rangeDate), function($q) use($rangeDate) {
                $q->where('master_teacher.begin_date', '<=', $rangeDate[0])->where('master_teacher.end_date', '>=', $rangeDate[1]);
            })
            ->when(!empty($request['search']['materials_date']),function($q) use($request){
                return $q->whereRaw("master_teacher.data_version_id in ({$request['search']['materials_date']})");
            })
            ->when($creatorName, function($q) use($creatorName) {
                $q->whereHas('creator', function ($query) use($creatorName) {
                    $query->where('nickname', 'like', '%' . $creatorName . '%');
                });
            })
            ->when($user->hasRole([2]), function($query) use($request,$user){
                $query->where(function ($q) {
                    $q->where('master_teacher.creator_id', Auth::id());
                })->orWhere(function ($q) use ($user) {
                    $q->where('master_teacher.user_id', Auth::id());
                    $q->where('b.status', '!=', 'FILL_IN');
                });
            })->when(!$user->hasRole([2]), function($query) use($user){
                $query->whereHas('instance', function ($query) {
                    $query->where('status', '!=','FILL_IN')
                        ->orWhere('master_teacher.creator_id', Auth::id());
                });
            })
            ->with('term', 'instance:id,status', 'creator')
            ->orderBy('master_teacher.id', 'desc')
            ->paginate($limit, '*', 'page', $page)
            ->toArray();

        return $result;
    }

    /**
     * @Description: 班主任添加
     * @Author: qiankun
     * @datetime: 2023-02-28
     */
    public function add($request)
    {
        $user = Auth::user();
        $term = Term::where('id', $request['data_version_id'])->first();
        $status = $request['status'] == 1 ? 'REVIEW' : 'FILL_IN';
        unset($request['status']);

        $dicArr = $this->dictionaryItemRepository->getDictionaryItem([$request['chief_value'], $request['grade_value'], $request['class_value']]);

        $chief = $dicArr->where('optionId', $request['chief_value'])->first();
        $grade = $dicArr->where('optionId', $request['grade_value'])->first();
        $class = $dicArr->where('optionId', $request['class_value'])->first();
        try{
            DB::beginTransaction();
            //添加状态
            $formInstance = FormInstance::create([
                'data_version_id' => $request['data_version_id'],
                'data_version_name' => $term->title,
                'form_key'=> $this->formKey,
                'type' => 'MainForm',
                'owner_id' => $user->id,
                'status' => $status,
                'creator_id' => $user->id,
            ]);

            //添加数据
            $request['user_id'] = $user->id;
            $request['creator_id'] = $user->id;
            $request['form_instance_id'] = $formInstance->id;
            $request['chief_value'] = json_encode([$chief->toArray()]);
            $request['grade_value'] = json_encode([$grade->toArray()]);
            $request['class_value'] = json_encode([$class->toArray()]);
            $result = MasterTeacher::create($request);
            //添加待办
            if($status == 'REVIEW'){
                Tasks::create([
                    'name' => '【' . $term->title . '】班主任管理-班主任审核',
                    'data_version_id' => $term->id,
                    'form_id' => $result->id,
                    'form_key' => $this->formKey,
                    'start_date' => date('Y-m-d H:i:s'),
                    'end_date' => $request['end_date'],
                    'creator_id' => $user->id,
                    'creator_name' => $user->nickname,
                    'param' => '?id=' . $result->id,
                    'url' => '/education/headmaster/check',
                    'menu_id'=> 395
                ]);
            }
            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return $result;
    }


    /**
     * @Description: 班主任单条数据
     * @Author: qiankun
     * @datetime: 2023-02-28
     */
    public function one($request)
    {
        if(!$request['id']) {
            throw new \Exception('ID参数缺失！');
        }

        $result = MasterTeacher::where('id', $request['id'])->with('creator', 'instance:id,status,comment')->first();

        return $result;
    }

    /**
     * @Description: 班主任编辑
     * @Author: kzj
     * @datetime: 2023-02-28
     */
    public function edit($request)
    {
        if(!$request['id']) {
            throw new \Exception('ID参数缺失！');
        }

        $status = 'REVIEW';
        $user = Auth::user();
        $term = Term::where('id', $request['data_version_id'])->first();
        $masterTeacher = MasterTeacher::whereId($request['id'])->first();

        $dicArr = $this->dictionaryItemRepository->getDictionaryItem([$request['chief_value'], $request['grade_value'], $request['class_value']]);

        $chief = $dicArr->where('optionId', $request['chief_value'])->first();
        $grade = $dicArr->where('optionId', $request['grade_value'])->first();
        $class = $dicArr->where('optionId', $request['class_value'])->first();

        try{
            DB::beginTransaction();

            //编辑状态
            FormInstance::whereId($masterTeacher->form_instance_id)->update([
                'data_version_id' => $request['data_version_id'],
                'data_version_name' => $term->title,
                'status' => $status,
                'updater_id' => $user->id
            ]);

            //编辑数据
            $request['updater_id'] = $user->id;
            $request['chief_value'] = json_encode([$chief->toArray()]);
            $request['grade_value'] = json_encode([$grade->toArray()]);
            $request['class_value'] = json_encode([$class->toArray()]);
            $result = MasterTeacher::whereId($request['id'])->update($request);

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return $result;
    }

    /**
     * @Description: 班主任删除
     * @Author: kzj
     * @datetime: 2023-02-28
     */
    public function del($request)
    {
        if(!$request['id']) {
            throw new \Exception('ID参数缺失！');
        }

        $result = MasterTeacher::whereId($request['id'])->update(['deleted' => 1]);

        return $result;
    }

    /*
     * @Description: 社会实践导出
     * @Author:  Kzj
     * @Date: 2023-11-17 14:43:04
     */
    public function export($request)
    {
        $termId = 0;
        $classId = 0;
        $chiefId = 0;
        $rangeDate = [];
        $creatorName = ''; //创建人
        $where = ['master_teacher.deleted' => 0];
        if (isset($request['search']['data_version_id'] )&& !empty($request['search']['data_version_id'])){
            $termId = $request['search']['data_version_id'];
        }
        if (isset($request['search']['class_value'] )&& !empty($request['search']['class_value'])){
            $classId = $request['search']['class_value'];
        }
        if (isset($request['search']['chief_value'] )&& !empty($request['search']['chief_value'])){
            $chiefId = $request['search']['chief_value'];
        }
        if (isset($request['search']['date_range'] )&& !empty($request['search']['date_range'])){
            $rangeDate = explode(' - ', $request['search']['date_range']);
        }
        if (isset($request['search']['creator_name'] )&& !empty($request['search']['creator_name'])){
            $creatorName = $request['search']['creator_name'];
        }
        $status = 'PASS';//导出的数据均为审核通过的
        $user = Auth::user();

        $output = MasterTeacher::where($where)->select('master_teacher.*')
            ->leftJoin('form_instance as b' ,'master_teacher.form_instance_id','=','b.id')
            ->when(!$user->is_checker, function($q) use($user){
                $q->where('master_teacher.user_id', $user->id);
            })
            ->when(isset($request['user_id']) && !empty($request['user_id']), function($q) use($request){
                $q->where('master_teacher.user_id', $request['user_id']);//处理档案袋只查看自己的数据
            })
            ->when($termId > 0, function($q) use($termId) {
                $q->whereHas('term', function ($query) use($termId) {
                    $query->where('id', $termId);
                });
            })
            ->when($classId > 0, function($q) use($classId) {
                $q->whereRaw(" JSON_EXTRACT(master_teacher.`class_value`,'$[0].optionId') = $classId");
            })
            ->when($chiefId > 0, function($q) use($chiefId) {
                $q->whereRaw(" JSON_EXTRACT(master_teacher.`chief_value`,'$[0].optionId') = $chiefId");
            })
            ->when(!empty($rangeDate), function($q) use($rangeDate) {
                $q->where('master_teacher.begin_date', '<=', $rangeDate[0])->where('master_teacher.end_date', '>=', $rangeDate[1]);
            })
            ->when(!empty($request['search']['materials_date']),function($q) use($request){
                return $q->whereRaw("data_version_id in ({$request['search']['materials_date']})");
            })
            ->when($creatorName, function($q) use($creatorName) {
                $q->whereHas('creator', function ($query) use($creatorName) {
                    $query->where('nickname', 'like', '%' . $creatorName . '%');
                });
            })
            ->when($status, function($q) use($status) {
                $q->where('b.status', '=', $status);
            })
            ->with('term', 'instance:id,status', 'creator')
            ->orderBy('master_teacher.id', 'desc')
            ->get();

        $title = ['学年学期','班级名称','正副情况','开始日期','结束日期','创建人','创建日期'];
        $exportData = [];
        foreach($output as $k => $v){
            $className = '';
            $gradeSet = !empty($v->grade_set) ? $v['grade_set'][0]['selectValue'] : '';
            $classSet = !empty($v->class_set) ? $v['class_set'][0]['selectValue'] : '';
            if($gradeSet || $classSet) {
                $className = $gradeSet . $classSet;
            }

            $item = [
                'term' => $v->data_version_id ? $v->term->title : '',
                'name' => $className,
                'zfqc' => !empty($v->chief_set) ? $v['chief_set'][0]['selectValue'] : '',
                'begin_date' => $v->begin_date,
                'end_date' => $v->end_date,
                'creator' => !empty($v->creator) ? $v->creator->nickname : '',
                'created_at' => $v->created_at
            ];

            $exportData[] = $item;
        }
        array_unshift($exportData, $title);

        $fileName = md5(auth()->user()->id.time()).'.xlsx';
        Excel::store(new ExcelExport($exportData), $fileName, 'excel');

        $result['file_name'] = $fileName;

        return $result;
    }

    /**
     * @Description: 班主任审核
     * @Author: qiankun
     * @datetime: 2025-03-26
     */
    public function check($request)
    {
        if(!$request['form_id']) {
            throw new \Exception('参数缺失！');
        }
        if(empty($request['status'])) {
            throw new \Exception('必须勾选审核结果！');
        }
        $user = Auth::user();

        try{
            DB::beginTransaction();

            $result = FormInstance::where('id', $request['form_instance_id'])
                ->update([
                    'status' => $request['status'],
                    'comment' => $request['comment'],
                    'updater_id'=> $user->id,
                ]);

            //修改待办事项
            Tasks::where('form_id', $request['form_id'])->where('form_key', $this->formKey)->update(['status' => 2]);

            //如果是驳回，重新给申报人发起待办事项
            if($request['status']== 'REVIEW_FAIL'){
                $task = Tasks::where('form_key', $this->formKey)->where('form_id', $request['form_id'])->where('type', 1)->orderBy('id', 'desc')->first();

                if($task) {
                    Tasks::create([
                        'name' => $task->name.'驳回',
                        'type' => 3,
                        'data_version_id' => $task['data_version_id'],
                        'form_id' => $task->form_id,
                        'form_key' => $this->formKey,
                        'start_date' => date('Y-m-d H:i:s'),
                        'end_date' => date('Y-m-d H:i:s'),
                        'c_user_id' => $task->creator_id,
                        'c_user_name' => $task->creator_name,
                        'creator_id' => $user->id,
                        'creator_name' => $user->nickname,
                        'param' => $task->param,
                        'url' => '/teaching/discipline/edit',
                        'menu_id' => 211
                    ]);
                }

            }

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return $result;
    }
}
